package boardgamer.yavalath.client.replaylobby;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import boardgamer.common.CyclicIterator;
import boardgamer.common.client.Button;
import boardgamer.common.client.HasEventHandler;
import boardgamer.common.client.animation.Screen;
import boardgamer.common.client.layout.LayoutGroup;
import boardgamer.common.net.PlayerId;
import boardgamer.yavalath.client.GoButton;
import boardgamer.yavalath.client.Header;
import boardgamer.yavalath.client.SharedObjects;
import boardgamer.yavalath.client.YavalathActivity;
import boardgamer.yavalath.client.resources.SoundHandler;
import boardgamer.yavalath.common.YavalathGameState;
import boardgamer.yavalath.common.YavalathPlayerState;
import boardgamer.yavalath.common.YavalathReplay;

import java.util.Map;

import static boardgamer.yavalath.client.lobby.LocalLobbyScreen.GO_HEIGHT_RATIO;
import static boardgamer.yavalath.client.lobby.LocalLobbyScreen.GO_TOP_RATIO;
import static boardgamer.yavalath.client.lobby.LocalLobbyScreen.MAX_PLAYER_COUNT;
import static boardgamer.yavalath.client.lobby.LocalLobbyScreen.PLAYERS_GAP_RATIO;
import static boardgamer.yavalath.client.lobby.LocalLobbyScreen.PLAYERS_TOP_RATIO;
import static boardgamer.yavalath.client.lobby.LocalLobbyScreen.PLAYERS_WIDTH_RATIO;

/**
 * @author garysoed
 */
public class ReplayLobbyScreen implements Screen {
  
  private static final float REPLAY_FILE_WIDTH_RATIO = 0.9f;
  private static final float REPLAY_FILE_TOP_GAP_RATIO = 0.05f;

  private Header header;
  private Button goButton;
  private ReplayFilePicker replayFilePicker;
  private ReplayPlayerDisplay[] playerDisplays;

  public ReplayLobbyScreen(YavalathActivity activity) {
    this.replayFilePicker = new ReplayFilePicker(activity, new ReplayFilePicker.PickedHandler() {
      @Override
      public void onReplayPicked(YavalathReplay replay) {
        // Hide all the player displays
        for (ReplayPlayerDisplay playerDisplay : playerDisplays) {
          playerDisplay.hide();
        }

        YavalathGameState initialGameState = replay.getInitialGameState();
        CyclicIterator<PlayerId> players
            = CyclicIterator.copyOf(initialGameState.getActivePlayers());
        Map<PlayerId, YavalathPlayerState> playerStates = initialGameState.getPlayerStates();
        for (int i = 0; i < players.size(); i++) {
          PlayerId currentPlayer = players.peek();
          playerDisplays[i].display(currentPlayer, playerStates.get(currentPlayer));
          players.next();
        }
      }
    });
  }

  @Override
  public void initialize(Rect canvasRect) {
    // Create Header
    header = new Header("Replay", canvasRect);

    // Create the replay file picker
    new LayoutGroup()
        .add(replayFilePicker).atCurrentRect()
        .setBoundingRect(
            new RectF(0, 0, canvasRect.width() * REPLAY_FILE_WIDTH_RATIO, canvasRect.height()));

    // Create the player buttons
    LayoutGroup playerGroup = new LayoutGroup();
    playerDisplays = new ReplayPlayerDisplay[MAX_PLAYER_COUNT];
    for (int i = 0; i < MAX_PLAYER_COUNT; i++) {
      this.playerDisplays[i] = new ReplayPlayerDisplay();
      if (i == 0) {
        playerGroup.add(this.playerDisplays[i]).atCurrentRect();
      } else {
        playerGroup.add(this.playerDisplays[i])
            .relativeToEdge(
                this.playerDisplays[i - 1],
                LayoutGroup.Direction.BOTTOM,
                canvasRect.height() * PLAYERS_GAP_RATIO);
      }
    }

    playerGroup.setBoundingRect(new RectF(
        0,
        canvasRect.height() * PLAYERS_TOP_RATIO,
        canvasRect.width() * PLAYERS_WIDTH_RATIO,
        canvasRect.height()),
        LayoutGroup.VerticalAlign.TOP,
        LayoutGroup.HorizontalAlign.LEFT);

    // Create Go button
    goButton = new GoButton(new HasEventHandler.EventHandler() {
      @Override
      public void onEvent(float eventX, float eventY, int eventAction) {
        if (eventAction == MotionEvent.ACTION_UP) {
          SoundHandler.playWave(SoundHandler.buttonSound);
          YavalathReplay pickedReplay = replayFilePicker.getPickedReplay();
          if (pickedReplay != null) {
            SharedObjects.instance().getProFeatures().startReplayView(pickedReplay);
          }
        }
      }
    });
    
    new LayoutGroup()
        .add(goButton).atCurrentRect()
        .setBoundingRect(new RectF(
            0,
            canvasRect.height() * GO_TOP_RATIO,
            canvasRect.width(),
            canvasRect.height() * (GO_TOP_RATIO + GO_HEIGHT_RATIO)));

    new LayoutGroup()
        .add(header).atCurrentRect()
        .add(replayFilePicker)
            .relativeToEdge(
                header,
                LayoutGroup.Direction.BOTTOM,
                REPLAY_FILE_TOP_GAP_RATIO * canvasRect.height());
  }

  @Override
  public void onOpen() {
    replayFilePicker.pickFile();
  }

  @Override
  public void onResume() { }

  @Override
  public void onUpdate(int elapsedTime) { }

  @Override
  public void onDraw(Canvas canvas) {
    header.draw(canvas);
    replayFilePicker.draw(canvas);
    goButton.draw(canvas);
    for (ReplayPlayerDisplay playerDisplay : playerDisplays) {
      playerDisplay.draw(canvas);
    }
  }

  @Override
  public void onTouchEvent(MotionEvent event) {
    replayFilePicker.handleEvent(event.getX(), event.getY(), event.getAction());
    goButton.handleEvent(event.getX(), event.getY(), event.getAction());
  }
}
